package com.lx.composetest

import android.media.MediaCodec
import android.media.MediaFormat
import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.IOException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.nio.ByteBuffer

class ThirdActivity : ComponentActivity() {

    private var codec: MediaCodec? = null
    private var socket: DatagramSocket? = null
    private val port = 44444

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            VideoReceiverUI()
        }
    }

    @Composable
    fun VideoReceiverUI() {
        var surfaceView: SurfaceView? by remember { mutableStateOf(null) }

        LaunchedEffect(Unit) {
            surfaceView?.holder?.addCallback(object : SurfaceHolder.Callback {
                override fun surfaceCreated(holder: SurfaceHolder) {
                    setupDecoder(holder)
                    startReceiving()
                }

                override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}

                override fun surfaceDestroyed(holder: SurfaceHolder) {
                    socket?.close()
                    codec?.stop()
                    codec?.release()
                }
            })
        }

        AndroidView(
            modifier = Modifier.fillMaxSize(),
            factory = { context ->
                SurfaceView(context).also { surfaceView = it }
            }
        )
    }

    private fun setupDecoder(holder: SurfaceHolder) {
        try {
            codec = MediaCodec.createDecoderByType("video/mp4")
            val format = MediaFormat.createVideoFormat("video/mp4", 1280, 720) // 修改为你的视频分辨率
            codec?.configure(format, holder.surface, null, 0)
            codec?.start()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun startReceiving() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                socket = DatagramSocket(port, InetAddress.getByName("0.0.0.0"))
                val buffer = ByteArray(1024)
                val packet = DatagramPacket(buffer, buffer.size)

                while (true) {
                    socket?.receive(packet)
                    decodePacket(buffer, packet.length)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    private fun decodePacket(data: ByteArray, length: Int) {
        val inputBuffer = codec?.getInputBuffer(codec!!.dequeueInputBuffer(10000))
        inputBuffer?.clear()
        inputBuffer?.put(data, 0, length)
        codec?.queueInputBuffer(codec!!.dequeueInputBuffer(10000), 0, length, 0, 0)

        val bufferInfo = MediaCodec.BufferInfo()
        val outputIndex = codec?.dequeueOutputBuffer(bufferInfo, 10000)
        if (outputIndex!! >= 0) {
            codec?.releaseOutputBuffer(outputIndex, true)
        }
    }
}
